package com.hawk.eye.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hawk.eye.framework.core.domain.model.LoginUser;
import com.hawk.eye.framework.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Optional;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        Optional<LoginUser> optionalLoginUser = SecurityUtils.getLoginUser(true);
        if (optionalLoginUser.isPresent()) {
            this.setFieldValByName("createUser", optionalLoginUser.get().getUser().getUserId(), metaObject);
            this.setFieldValByName("updateUser", optionalLoginUser.get().getUser().getUserId(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        Optional<LoginUser> optionalLoginUser = SecurityUtils.getLoginUser(true);
        if (optionalLoginUser.isPresent()) {
            this.setFieldValByName("updateUser", optionalLoginUser.get().getUser().getUserId(), metaObject);
        }
    }
}
